package net.apexes.wsonrpc.demo.client;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * @author <a href="mailto:hedyn@foxmail.com">HeDYn</a>
 *
 */
public class DemoWsonrpcClient {
    
    private static final Logger LOG = LoggerFactory.getLogger(DemoWsonrpcClient.class);

    public static void main(String[] args) throws Exception {
        runClient();
    }

    static void runClient() throws Exception {
        WsonrpcClientWarpper client = null;
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
            while (true) {
                System.out.print(">");
                String command = reader.readLine();
                if (command.isEmpty()) {
                    continue;
                }
                try {
                    if (command.startsWith("connect ")) {
                        String clientId = command.substring("connect ".length());
                        if (clientId.isEmpty()) {
                            continue;
                        }
                        if (client == null) {
                            client = new WsonrpcClientWarpper(clientId);
                            client.connect();
                        }
                    } else if ("disconnect".equalsIgnoreCase(command)) {
                        if (client != null) {
                            client.disconnect();
                        }
                    } else if ("exit".equalsIgnoreCase(command)) {
                        break;
                    } else if ("login".equalsIgnoreCase(command)) {
                        if (client != null) {
                            client.login("admin", "admin123");
                        }
                    } else if ("ping".equalsIgnoreCase(command)) {
                        if (client != null) {
                            client.ping();
                        }
                    } else if ("demo".equalsIgnoreCase(command)) {
                        if (client != null) {
                            client.demo();
                        }
                    } else if ("error".equalsIgnoreCase(command)) {
                        if (client != null) {
                            client.error();
                        }
                    }
                } catch (Exception e) {
                    LOG.error("", e);
                }
            }
        } finally {
            if (client != null) {
                client.close();
            }
        }
        LOG.info("closed");
    }

}
